package com.bff.gaia.streaming.api.mo.gaia.io.basiccoder;

import java.io.*;
import java.util.Arrays;

//字节数组输出流在内存中创建一个字节数组缓冲区，所有发送到输出流的数据保存在该字节数组缓冲区中。

public class StringDoubleArrayCoder {
	private String cmd;
	private String string;
	private Double[] val;
	private byte[] data;

	public String getCmd() {
		return this.cmd;
	}
	public void setCmd(String cmd) {
		this.cmd = cmd;
	}
	public String getString() {
		return this.string;
	}
	public Double[] getDoubleArray() {
		return this.val;
	}
	public byte[] getBytes() {
		return this.data;
	}
	public StringDoubleArrayCoder(String string, Double[] val, String cmd) {
		this.string = string;
		this.val = val;
		this.cmd = cmd;
		this.makeBytes();
	}

	public StringDoubleArrayCoder(byte[] data) {
		this.data = data;
		this.makeValue();
	}

	private void makeValue() {

		DataInputStream din = new DataInputStream(new ByteArrayInputStream(this.data));

		try {
			int cmdlen = din.readInt();
			byte[] cmddata = new byte[cmdlen];

			din.readFully(cmddata);

			StringCoder cmdcoder = new StringCoder(cmddata);
			this.cmd = cmdcoder.getString();

			int strlen = din.readInt();
			byte[] strdata = new byte[strlen];
			din.readFully(strdata);
			StringCoder strcoder = new StringCoder(strdata);
			this.string = strcoder.getString();

			int doublelen = din.readInt();
			byte[] doubledata = new byte[doublelen];
			din.readFully(doubledata);

			DoubleArrayCoder doublecoder = new DoubleArrayCoder(doubledata);
			this.val = doublecoder.getDoubleArray();

		} catch (IOException var11) {
			var11.printStackTrace();
		}

	}

	private void makeBytes() {

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(bos);

		StringCoder cmdcoder = new StringCoder(this.cmd);
		StringCoder strcoder = new StringCoder(this.string);
		DoubleArrayCoder dcoder = new DoubleArrayCoder(this.val);

		byte[] cmddata = cmdcoder.getBytes();
		byte[] strdata = strcoder.getBytes();
		byte[] doubledata = dcoder.getBytes();

		try {
			dos.writeInt(cmddata.length);
			dos.write(cmddata);
			dos.writeInt(strdata.length);
			dos.write(strdata);
			dos.writeInt(doubledata.length);
			dos.write(doubledata);
		} catch (IOException var10) {
			var10.printStackTrace();
		}

		this.data = bos.toByteArray();
	}

	@Override
	public String toString() {
		return "StringDoubleArrayCoder{" +
			"cmd='" + cmd + '\'' +
			", string='" + string + '\'' +
			", val=" + Arrays.toString(val) +
			", data=" + Arrays.toString(data) +
			'}';
	}
}
